<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import {onBeforeUnmount, ref, shallowRef} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'

const emits = defineEmits();

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  height: {
    type: Number,
    default: null
  },
})

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('')

const toolbarConfig = {}
const handleChange = (editor) => {
  const html = editor.getHtml()
  console.log(html)
  emits("update:modelValue", html);
}

const editorConfig = {
  placeholder: '请输入内容...',
  height: props.height,
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
  console.log("销毁")
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

watch(() => props.modelValue, val => {
  console.log(val, "val")

  if (val) {
    // 首先将值转为数组
    valueHtml.value = val
  } else {
    valueHtml.value = '';
    return [];
  }
}, {deep: true, immediate: true});

</script>

<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        mode="default"
    />
    <Editor
        :style="{
      height: editorConfig.height + 'px',
      overflowY: 'hidden',

        }"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        mode="default"
        @onChange="handleChange"
        @onCreated="handleCreated"
    />
  </div>
</template>

<style scoped lang="scss">

</style>
